<%-- 
   * 【描 述】：用户管理页面
   * 【环 境】：JAVA 1.7.0_13
   *  @author         柴志鹏  CHAIZP@GMAIL.COM
   *  @version        v1.0 2014-06-27
   *  @since          2014-06-27
 --%>
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ include file="/include/head.jsp"%>

<html>
  <head>
    <title>用户管理</title>
    <script type="text/javascript">
    	Ext.onReady(function(){
    		Ext.QuickTips.init();
	    	Ext.form.Field.prototype.msgTarget = 'qtip';
	    	
	    	var personStore = new Ext.data.Store({//人员数据源
				proxy: new Ext.data.HttpProxy({
					url: 'PersonAction!getPersonList.do'
				}),
				reader: new Ext.data.JsonReader({
					totalProperty: 'total',
					root: 'list'
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
					{name: 'personCode'},
					{name: 'personName'},
					{name: 'sex'},
					{name: 'birthday', type: 'date'},
					{name: 'height'},
					{name: 'weight'},
					{name: 'waistline'},
					{name: 'shirtSize'},
					{name: 'necklineSize'},
					{name: 'email'},
					{name: 'mobile'},
					{name: 'insideNum'}
				])),
				remoteSort: false,//是否远程排序
				autoLoad: {
					params:{
						start: PAGING_START_INDEX,
						limit: PAGING_PAGE_SIZE
					}
				}
			});
	    	
	    	var personModel = new Ext.grid.CheckboxSelectionModel({
	    		singleSelect: true,//单选
	    		header: '',//空来代替checkbox全选框
		    	listeners: {
	    			rowselect: function(selModel, rowIndex, record) {//行选中
						userStore.baseParams = {//根据人员Id查询用户
							personId: record.get('id')
						};
						userStore.reload({
							callback: function(record, options, success) {//回调函数
								if(success) {//存在用户
									Ext.getCmp('userForm').getForm().loadRecord(record[0]);
									Ext.getCmp('addBtn').hide();
									Ext.getCmp('modifyBtn').show();
									Ext.getCmp('deleteBtn').show();
								} else {//不 存在
									Ext.getCmp('userForm').getForm().reset();
									Ext.getCmp('addBtn').show();
									Ext.getCmp('modifyBtn').hide();
									Ext.getCmp('deleteBtn').hide();
								}
							}
						});
						roleStore.baseParams = {//根据人员Id查询角色
							personId: record.get('id')
						};
						roleStore.reload();
						menuStore.baseParams = {//根据人员Id查询菜单
							personId: record.get('id')
						};
						menuStore.reload();
	    			}
		    	}
	    	});
	    	var personCol = new Ext.grid.ColumnModel({
	    		id: 'column',
	    		defaults: {
	    			sortable: true,//默认全部列可排序
	    			align: 'center'
	    		},
	    		columns: [
	    			personModel,
	    			new Ext.grid.RowNumberer({
	    				id: 'rownum',
	    				header: '序号',
	    				width: 40
	    			}),{
	    				id: 'id',
	    				header: '主键Id',
	    				dataIndex: 'id',
	    				width: 50,
	    				hidden: true
	    			},{
	    				id: 'personName',
	    				header: '姓名',
	    				dataIndex: 'personName',
	    				width: 50
	    			},{
	    				id: 'sex',
	    				header: '性别',
	    				dataIndex: 'sex',
	    				width: 40,
	    				renderer: function(value, cellmeta, record) {
			        		return ['女', '男'][value];
			        	}
	    			},{
	    				id: 'birthday',
	    				header: '生日',
	    				dataIndex: 'birthday',
	    				renderer: Ext.util.Format.dateRenderer(SHORT_DATE_FORMAT),
	    				width: 60
	    			},{
	    				id: 'height',
	    				header: '身高(cm)',
	    				dataIndex: 'height',
	    				width: 30
	    			},{
	    				id: 'weight',
	    				header: '体重(kg)',
	    				dataIndex: 'weight',
	    				width: 30
	    			},{
	    				id: 'waistline',
	    				header: '腰围(尺)',
	    				dataIndex: 'waistline',
	    				width: 30
	    			},{
	    				id: 'shirtSize',
	    				header: '衬衫尺寸',
	    				dataIndex: 'shirtSize',
	    				width: 50
	    			},{
	    				id: 'necklineSize',
	    				header: '领口尺寸',
	    				dataIndex: 'necklineSize',
	    				width: 50
	    			},{
	    				id: 'email',
	    				header: '邮箱',
	    				dataIndex: 'email',
	    				width: 80
	    			},{
	    				id: 'mobile',
	    				header: '移动电话',
	    				dataIndex: 'mobile',
	    				width: 70
	    			},{
	    				id: 'insideNum',
	    				header: '内线号',
	    				dataIndex: 'insideNum',
	    				width: 50
	    			}
	    		]
	    	});
	    	
	    	var userStore = new Ext.data.Store({//童虎数据源
				proxy: new Ext.data.HttpProxy({
					url: 'UserAction!getUserInfoByPid.do'
				}),
				reader: new Ext.data.JsonReader({}, 
					new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
					{name: 'personId'},
					{name: 'username'},
					{name: 'password'},
					{name: 'name'},
					{name: 'createDate', type: 'date'},
					{name: 'passPrompt'},
					{name: 'enableStatus'},
					{name: 'remark'}
				])),
				remoteSort: false,//是否远程排序
				autoLoad: false
			});
	    	
	    	var roleStore = new Ext.data.Store({//角色数据源
				proxy: new Ext.data.HttpProxy({
					url: 'UserAction!queryRelationRole.do'
				}),
				reader: new Ext.data.JsonReader({
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
		        	{name: 'roleName'},
				    {name: 'enableStatus'},
				    {name: 'checked'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: false
			});
	    	
	    	var roleModel = new Ext.grid.CheckboxSelectionModel();
	    	var roleCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true // 默认全部列可排序          
		        },
		        columns: [
		        	roleModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50,
						align: 'center'	
					}),{
		        		id: 'roleId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						align: 'center',
						hidden: true
					},{
		        		id: 'roleName',
			        	header: '角色名称',
			        	dataIndex: 'roleName',
			      		width: 80,
			           	align: 'center'
			        },{
			        	id: 'enableStatus',
			        	header: '状态',
			        	dataIndex: 'enableStatus',
			        	width: 60,
			        	align: 'center',
			        	renderer: function(value, cellmeta, record) {
			        		return ['<span style="color:red;font-weight:bold;">禁用</span>',
			        				'<span style="color:green;font-weight:bold;">启用</span>']
			        				[value];
			        	}
			        }
		        ]
		    });
	    	
	    	var menuStore = new Ext.data.Store({//菜单数据源
				proxy: new Ext.data.HttpProxy({
					url: 'UserAction!queryRelationMenu.do'
				}),
				reader: new Ext.data.JsonReader({
				}, new Ext.data.Record.create([
					{name: 'cudType'},
					{name: 'id'},
		        	{name: 'text'},
				    {name: 'enableStatus'}
				])),
				//sortInfo: {field: 'id', direction: 'ASC'},
				remoteSort: false,//是否远程排序
				autoLoad: false
			});
	    	
	    	var menuModel = new Ext.grid.CheckboxSelectionModel();
	    	var menuCol = new Ext.grid.ColumnModel({
	    		defaults: {
		            sortable: true // 默认全部列可排序          
		        },
		        columns: [
		        	roleModel,
		        	new Ext.grid.RowNumberer({
		        		id: 'rownum',
		        		header: '序号',
						width: 50,
						align: 'center'	
					}),{
		        		id: 'menuId',
						header: '主键ID',
						dataIndex: 'id',
						width: 25,
						align: 'center',
						hidden: true
					},{
		        		id: 'text',
			        	header: '角色名称',
			        	dataIndex: 'text',
			      		width: 80,
			           	align: 'center'
			        },{
			        	id: 'enableStatus',
			        	header: '状态',
			        	dataIndex: 'enableStatus',
			        	width: 60,
			        	align: 'center',
			        	renderer: function(value, cellmeta, record) {
			        		return ['<span style="color:red;font-weight:bold;">禁用</span>',
			        				'<span style="color:green;font-weight:bold;">启用</span>']
			        				[value];
			        	}
			        }
		        ]
		    });
	    	
	    	//////////////////////////////////////////////////
	    	var viewport = new Ext.Viewport({
	    		layout: 'border',
	    		items: [
	    			new Ext.grid.GridPanel({
	    				id: 'personGrid',
	    				region: 'west',
	    				autoScroll: true,
					    store: personStore,
					    cm: personCol,
					    sm: personModel,
					    frame: false,
					    trackMouseOver: true,//鼠标经过痕迹
					    loadMask: true,
			        	loadMask: {msg: 'loading...'},
			        	viewConfig: {
			        		forceFit: true,//根据column进行百分比设置
			        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
			        	},
			        	bbar: cf_getPagingToolbar(PAGING_PAGE_SIZE, personStore),
			        	listeners: {
			        		resize: function(){//窗体调整
			        			var parentWidth = window.parent.document.body.clientWidth;//父窗口宽度
			        			if(document.body.clientWidth == parentWidth) {//当最大化时将全部列显示
			        				isColumnVisible(this, false);
			        			} else {
			        				isColumnVisible(this, true);
			        			}
			        		},
			        		rowdblclick: function(grid, rowIndex, event) {//双击事件
			        			var record = grid.getStore().getAt(rowIndex);
     							personController('U', '修改', record);
			        		},
			        		afterrender: function(grid) {//渲染后
		        				if(grid.getStore().getCount() > 0) {//默认选中首行
			        				grid.getSelectionModel().selectRow(0);
			        			}
			        		}
			        	},
			        	tbar: [
			        		{
			        			text: '新增',
			        			iconCls: 'addBtn',
			        			handler: function() {
			        				personController('C', this.text);
			        			}
			        		},{
			        			text: '修改',
			        			iconCls: 'editBtn',
			        			handler: function() {
			        				var grid = Ext.getCmp('personGrid');
						    		var record = grid.getSelectionModel().getSelected();
			        				if(record) {
			        					personController('U', this.text, record);
					            	} else {
					            		Ext.MessageBox.alert('提示', '请选择一条记录.');
					            	}
			        			}
			        		},{
			        			text: '删除',
			        			iconCls: 'deleteBtn',
			        			handler: function() {
			        				var grid = Ext.getCmp('personGrid');
						    		var record = grid.getSelectionModel().getSelected();
			        				if(record) {
										Ext.MessageBox.confirm('提示', '确认删除?',
											function(btn) {
												if(btn == BUTTON_YES) {
													Ext.Ajax.request({
														url: 'PersonAction!personController.do',
														method: 'POST',
														params: {
															'person.cudType': 'D',
														    'person.id': record.get('id'),
														    'userId': Ext.getCmp('userForm').getForm().findField('id').getValue()
														    //'person.optUserId': userId,
														    //'person.optUserName': userName
														},
														success: function(result, request){
															personStore.remove(record);
															refresh();
														},
														failure: function(result, request){
														    Ext.Msg.alert('提示','操作失败!请重试.');
														}
													});
												}
											}
									    )
					            	} else {
					            		Ext.MessageBox.alert('提示', '请选择一条记录.');
					            	}
			        			}
			        		},'->','姓名',
				        	new Ext.form.TwinTriggerField({
							    trigger1Class: 'x-form-clear-trigger',
							    trigger2Class: 'x-form-search-trigger',
							    hideTrigger1: true,
							    autoWidth: true,
							    listeners: {
							        'specialkey': function(f, e){
							        	if(e.getKey() == e.ENTER){
							            	this.onTrigger2Click();
							        	}
							    	}
							 	},
							 	onTrigger1Click:function(){
							    	this.setRawValue('');
							     	this.triggers[0].hide();
							    	return false;
							 	},
							 	onTrigger2Click:function(){
							    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
						        	this.triggers[0].show();
							    	var store = Ext.getCmp('personGrid').getStore();
							        store.reload({
							        	params: {
							        		start: PAGING_START_INDEX,
											limit: PAGING_PAGE_SIZE,
							        		personName: name
							        	}
							    	});
								}
							})
			        	]
	    			}),
	    			new Ext.TabPanel({
	    				id:'tabs',
				 	    region: 'center',
					    deferredRender: false,
					    activeTab: 0,
					    bodyBorder: false,
					    enableTabScroll: true,  
					    frame: true,
					    defaults: {
	    					autoScroll: false
	    				},
	    				items: [
	    					{
	    						id: 'userInfoTab',
								title: '用户信息',
								items: new Ext.form.FormPanel({
						            id: 'userForm',
						            region: 'center',
						            autoScroll: true,
						            layout: 'column',
						            labelWidth: 80,
						            labelAlign: 'right',
						            width: 300,
					            	height: 330,
						            border: false,
						            buttonAlign: 'center',
						            layout: 'form',
						            defaults: {
										anchor: '90%'
						            },
						            items:[
							            {
							            	border: false,
							            	html: '<p>用户信息</p>',
							            	style: 'font-size: 20px; text-align: center; padding: 5 5 5 5;'
							            },
							            new Ext.form.Hidden({
							        		name: 'id'
							            }),
							            new Ext.form.TextField({
											fieldLabel: '用户名',
											name: 'username',
											maxLength: 20,
											maxLengthText: '用户名长度不可大于{0}字符',
											readOnly: true
										}),
										new Ext.form.Hidden({
							        		name: 'password'
							            }),
										new Ext.form.TextField({
											fieldLabel: '姓名',
											name: 'name',
											maxLength: 10,
											maxLengthText: '姓名长度不可大于{0}字符',
											readOnly: true
										}),
										new Ext.form.DateField({
											fieldLabel: '创建日期',
											name: 'createDate',
											format: SHORT_DATE_FORMAT,
											readOnly: true,
											editable: false
										}),
										new Ext.form.TextField({
											fieldLabel: '密码提示',
											name: 'passPrompt',
											maxLength: 50,
											maxLengthText: '密码提示长度不可大于{0}字符',
											readOnly: true
										}),
										new Ext.form.RadioGroup({
											fieldLabel:'使用状态',
											columns: [50,50],// 列间距
					            			items: [
					            				{boxLabel: '启用', inputValue: 1, name: 'enableStatus', checked: true},
					            				{boxLabel: '禁用', inputValue: 0, name: 'enableStatus'}
					            			]
										}),
										new Ext.form.TextArea({
											fieldLabel: '备注',
											name: 'remark',
											readOnly: true
										})
							        ],
									buttons: [{
										id: 'addBtn',
						                text: '创建用户',
						                handler: function() {
											var record = getSelectPersonInfo();
											if(record) {
												userController('C', this.text, record.get('id'));
											} else {
												Ext.MessageBox.alert('提示', '请选择相应人员.');
											}
						                }
						            },{
						            	id: 'modifyBtn',
						                text: '编辑用户',
						                handler: function() {
						            		var record = getSelectPersonInfo();
											if(record) {
												userController('U', this.text, record.get('id'));
											} else {
												Ext.MessageBox.alert('提示', '请选择相应人员.');
											}
						                }
						            },{
						            	id: 'deleteBtn',
						                text: '删除用户',
						                handler: function() {
						            		var record = getSelectPersonInfo();
						            		if(record) {
						            			Ext.MessageBox.confirm('提示', '确定删除此用户?', this.doDelete);
						            		} else {
						            			Ext.MessageBox.alert('提示', '请选择相应人员.');
						            		}
						                },
						                doDelete: function(btn) {
						                	if(btn == BUTTON_YES) {
						                		var userId = Ext.getCmp('userForm').getForm().findField('id').getValue();
				                    			Ext.Ajax.request({
							                        url: 'UserAction!userController.do',
							                        method: 'POST',
							                        params: {
							                        	'user.cudType': 'D',//Delete
							                        	'user.id': userId
							                            //'optUserId': '1',
							                            //'optUserName': '超级管理员'
							                        },
							                        success: function(result, request){
							                        	refresh();
							                        },
							                        failure: function(result, request){
							                            Ext.Msg.alert('提示','操作失败!请重试.');
							                        }
							                    });
				                    		}
						                }
						            }]
			            		})
	    					},{
	    						id: 'belongsRoleTab',
								title: '所属角色',
								html: '<div id="belongsRole" style="height:100%"></div>'
	    					},{
	    						id: 'menuAuthorizeTab',
								title: '菜单权限',
								html: '<div id="menuAuthorize" style="height:100%"></div>'
	    					}
	    				],
	    				listeners: {
	    					tabchange: function(tabPanel, panel) {
	    						if(panel.getItemId() == 'belongsRoleTab') {
	    							roleGrid.render();
	    						} else if(panel.getItemId() == 'menuAuthorizeTab') {
	    							menuGrid.render();
	    						}
	    						
	    					}
	    				}
	    			})
	    		],
	    		listeners: {
	    			resize: function(viewport, adjWidth, adjHeight, rawWidth, rawHeight) {
	    				var west = Ext.getCmp('personGrid');
	    				if(Ext.isIE) {
	    					west.setWidth((adjWidth=='auto'?700:adjWidth)*0.6);
	    				} else {
	    					west.setWidth('60%');
	    				}
					}
	    		}
	    	});
	    	
	    	roleGrid = new Ext.grid.GridPanel({
	        	id: 'roleGrid',
	        	el: 'belongsRole',
		        autoScroll: true,
		        autoHeight: true,
		        autoWidth: true,
			    store: roleStore,
			    cm: roleCol,
			    sm: roleModel,
			    border: false,
			    frame: false,
			    trackMouseOver: true,//鼠标经过痕迹
			    loadMask: true,
	        	loadMask: {msg: 'loading...'},
			    viewConfig: {
	        		forceFit: true,//根据column进行百分比设置
	        		scrollOffset: 0
	        	},
	        	tbar: [
	        		new Ext.Button({
	        			text: '授权角色',
	        			iconCls: 'addBtn',
	        			handler: function() {
	        				var record = getSelectPersonInfo();
	        				if(record) {
	        					roleAuthorization(this.text, record.get('id'));
	        				} else {
	        					Ext.MessageBox.alert('提示', '请选择相应人员.');
	        				}
	        			}
	        		}),
	        		new Ext.Button({
	        			text: '取消授权',
	        			iconCls: 'deleteBtn',
	        			handler: function() {
	        				var records = roleGrid.getSelectionModel().getSelections();
					        if (records.length > 0) {
						        Ext.MessageBox.confirm('提示', '确定取消授权角色?',
									function(btn) {
									    if(btn == BUTTON_YES) {
									    	cf_ShowMessageBox('删除中..');
									    	var personId = getSelectPersonInfo().get('id');
									        var data = "[";
									        for (var i = 0, len = records.length; i < len; i++){
									        	roleGrid.getStore().remove(records[i])
									            data = data + "{personId:'"+ personId +
									            	"', roleId:'" + records[i].get('id') +"'}";
									            if (i < len - 1) {	data = data + ",";}
									        }
											data = data + "]";
											
											Ext.Ajax.request({
												url: 'UserAction!deleteRelationRole.do',
												method: 'POST',
												params: {jsonData: data},
												success: function (result, request) {
													Ext.MessageBox.alert('操作成功', '共：'+ result.responseText +'条角色被取消授权.',
														function(btn) {
															refresh();
														}
													);
												},
												failure: function (result, request) {
													Ext.MessageBox.alert('提示', '操作失败!');
									            }
											});
							         	}
									}
						        );
					        } else {
					            Ext.MessageBox.alert('提示', '请选择要取消授权的角色.');
					            return false;			        
					        }
	        			}
	        		})
	        	]
			});
	    	
	    	menuGrid = new Ext.grid.GridPanel({
	        	id: 'menuGrid',
	        	el: 'menuAuthorize',
		        autoScroll: true,
		        autoHeight: true,
		        autoWidth: true,
			    store: menuStore,
			    cm: menuCol,
			    sm: menuModel,
			    border: false,
			    frame: false,
			    trackMouseOver: true,//鼠标经过痕迹
			    loadMask: true,
	        	loadMask: {msg: 'loading...'},
			    viewConfig: {
	        		forceFit: true,//根据column进行百分比设置
	        		scrollOffset: 0
	        	}
			});
	    	
	    	function isColumnVisible(grid, isVis) {
	   			grid.getColumnModel().setHidden(5, isVis);
	   			grid.getColumnModel().setHidden(6, isVis);
	   			grid.getColumnModel().setHidden(7, isVis);
	   			grid.getColumnModel().setHidden(8, isVis);
	   			grid.getColumnModel().setHidden(9, isVis);
	   			grid.getColumnModel().setHidden(10, isVis);
	   			grid.getColumnModel().setHidden(11, isVis);
		    }
	    	
	    	function personController(cudType, title, record) {
	    		var personForm = new Ext.form.FormPanel({
		            id: 'personForm',
		            region: 'center',
		            autoScroll: true,
		            layout: 'column',
		            labelWidth: 70,
		            autoWidth: true,
		            labelAlign: 'right',
		            bodyStyle: 'padding:5px 5px 0',
		            border: true,
		            frame: true,
		            fileUpload: true,
		            buttonAlign: 'center',
		            defaults: {
				        layout: 'form',
				        columnWidth: .50,
				        labelWidth: 60,
				        defaults: {
				            anchor: '90%'
				        }
				    },
		            items:[{
				        items: [
				        	new Ext.form.Hidden({
				        		id: 'id',
				            	name: 'person.id'
				            }),
				            new Ext.form.TextField({
								fieldLabel: cf_getRequiredItem('姓名'),
								id: 'personName',
				            	name: 'person.personName',
				            	maxLength: 10,
								maxLengthText: '姓名长度不可大于{0}字符',
								allowBlank: false,
								regex: /^[\u4E00-\u9FA5]+$/,
								regexText: '格式错误-示例: 张无忌'
							}),
							new Ext.form.RadioGroup({// 单选按钮
								fieldLabel:'性别',
								id: 'sex',
								columns: [50,50],// 列间距
			           			items: [
			           				{boxLabel: '男', inputValue: 1, name: 'person.sex', checked: true},
			           				{boxLabel: '女', inputValue: 0, name: 'person.sex'}
			           			]
							}),
							new Ext.form.DateField({
								fieldLabel: '生日',
								id: 'birthday',
								name: 'person.birthday',
								format: SHORT_DATE_FORMAT,
								editable: false
							}),
							new Ext.form.NumberField({
								fieldLabel: '身高(cm)',
								id: 'height',
								name: 'person.height',
								maxLength: 10,
								maxLengthText: '身高长度不可大于{0}字符'
							}),
							new Ext.form.NumberField({
								fieldLabel: '体重(kg)',
								id: 'weight',
								name: 'person.weight',
								maxLength: 10,
								maxLengthText: '体重长度不可大于{0}字符'
							}),
							new Ext.form.NumberField({
								fieldLabel: '腰围(尺)',
								id: 'waistline',
								name: 'person.waistline',
								maxLength: 10,
								maxLengthText: '腰围长度不可大于{0}字符'
							})
				        ]
				    },{
				        items: [
				        	new Ext.form.TextField({
								fieldLabel: '编号',
								id: 'personCode',
								name: 'person.personCode',
								maxLength: 50,
								maxLengthText: '编号长度不可大于{0}字符'
							}),
				        	new Ext.form.NumberField({
								fieldLabel: '内线号',
								id: 'insideNum',
								name: 'person.insideNum',
								maxLength: 20,
								maxLengthText: '内线号长度不可大于{0}字符'
							}),
				        	new Ext.form.NumberField({
								fieldLabel: '移动电话',
								id: 'mobile',
								name: 'person.mobile',
								regex: /^1[3|4|5|7|8][0-9]\d{8}$/,
		    					regexText: '非手机号码-示例:13999999999'
							}),
							new Ext.form.TextField({
								fieldLabel: '衬衫尺寸',
								id: 'shirtSize',
								name: 'person.shirtSize',
								maxLength: 10,
								maxLengthText: '衬衫尺寸长度不可大于{0}字符'
							}),
							new Ext.form.NumberField({
								fieldLabel: '领口尺寸',
								id: 'necklineSize',
								name: 'person.necklineSize',
								maxLength: 10,
								maxLengthText: '领口尺寸长度不可大于{0}字符'
							}),
							new Ext.form.TextField({
								fieldLabel: '邮箱',
								id: 'email',
								name: 'person.email',
								regex: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
								regexText: '非邮箱格式-示例: admin@czp.com'
							})
				        ]
				    }],
		            buttons: [{
		                text: '保存',
		                handler: function() {
		                    if(!(personForm.form.isValid())) {
		                    	return false;
		                    } else {
		                    	personForm.getForm().submit({
									url: 'PersonAction!personController.do',
									method: 'POST',
									submitEmptyText: false,
									params: {
										'person.cudType': cudType
						    		//	'optUserId': '1',
						    		//	'optUserName': '超级管理员'
									},
									success: function (result, request) {
										win.hide('userManager', function() {	// 淡入窗口
											refresh();	// 刷新
						                	win.close();						// 关闭
						                }, true);
									},
									failure: function (result, request) {
										Ext.MessageBox.alert('提示', '操作失败!');
						            }
								});
		                    }
		                }
		            },{
		                text: '取消',
		                handler: function() {
		                    win.hide('userManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
		                }
		            }]
		        });
	    		
	    		win = new Ext.Window({
		            title: title,
		            layout: 'border',
		            width: 450,
		            height: 250,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: personForm,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					listeners: {
		        		show: function(win) {
		        			if (record) {
								personForm.getForm().loadRecord(record);
							}
		        		}
		            }
		        });
		        win.show('userManager');// 淡出窗口
		        
	    	}
	    	
	    	function userController(cudType, title, personId) {
	    		Ext.apply(Ext.form.VTypes, {
	                password: function(val, field) {
	                    if (field.initialPassField) {
	                        var pwd = Ext.getCmp(field.initialPassField);
	                        return (val == pwd.getValue());
	                    }
	                    return true;
	                },
	                passwordText: '两次输入的密码不一致!',
	                isUserExist: function(val, field) {
	                	return true;
	                },
	                isUserExistText: '用户名已存在.'
	            });
	    		
	    		var userWinForm = new Ext.form.FormPanel({
		            id: 'userWinForm',
		            region: 'center',
		            autoScroll: true,
		            layout: 'form',
		            labelWidth: 70,
		            labelAlign: 'right',
		            bodyStyle: 'padding:5px 5px 0',
		            border: true,
		            frame: true,
		            fileUpload: true,
		            buttonAlign: 'center',
		            defaults: {
						anchor: '90%'
		            },
		            items:[
		            	new Ext.form.Hidden({
			        		itemId: 'id',
			            	name: 'user.id'
			            }),
			            new Ext.form.Hidden({
			        		itemId: 'personId',
			            	name: 'user.personId',
			            	value: personId
			            }),
			            new Ext.form.TextField({
							fieldLabel: cf_getRequiredItem('用户名'),
							itemId: 'username',
			            	name: 'user.username',
			            	validateOnBlur: false,//是否当失去焦点时验证此表单元素
							allowBlank: false,
							listeners: {
			            		change: function(field, newValue, oldValue) {
			            			Ext.Ajax.request({
			            				url: 'UserAction!isUserExist.do',
			            				method: 'POST',
			            				params: {'username': newValue},
			            				success: function(result, request) {
			            					if(result.responseText) {
			            						field.markInvalid('该用户名已存在.');
			            						isExist = true;
			            					} else {
			            						isExist = false;
			            					}
										},
										failure: function(result, request) {
										    Ext.Msg.alert('提示','操作失败!请重试.');
										}
			            			});
			            		}
							}
						}),
						new Ext.form.TextField({
							fieldLabel: cf_getRequiredItem('密码'),
							id: 'password',
			            	name: 'user.password',
			            	inputType: 'password',
							allowBlank: false,
							listeners: {
		            			afterrender: function(text) {
		            				if(cudType == 'U') {//修改
		            					Ext.getCmp('confirm').setValue(text.getValue());
		            				}
		            			}
							}
						}),
		            	new Ext.form.TextField({
							fieldLabel: cf_getRequiredItem('密码确认'),
							id: 'confirm',
							inputType: 'password',
							vtype : 'password',
                            initialPassField: 'password',
							allowBlank: false
						}),
						new Ext.form.TextField({
							fieldLabel: '密码提示',
							itemId: 'passPrompt',
			            	name: 'user.passPrompt'
						}),
						new Ext.form.TextField({
							fieldLabel: '姓名',
							itemId: 'name',
			            	name: 'user.name'
						}),
						new Ext.form.RadioGroup({// 单选按钮
							fieldLabel: '使用状态',
							itemId: 'enableStatus',
							columns: [50,50],// 列间距
		           			items: [
		           				{boxLabel: '启用', inputValue: 1, name: 'user.enableStatus', checked: true},
		           				{boxLabel: '禁止', inputValue: 0, name: 'user.enableStatus'}
		           			]
						}),
						new Ext.form.TextArea({
							fieldLabel: '备注',
							itemId: 'remark',
							name: 'user.remark'
						})
		            ]
		        });
	    		
	    		win = new Ext.Window({
		            title: title,
		            layout: 'border',
		            width: 350,
		            height: 320,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: userWinForm,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					buttonAlign: 'center',
					buttons: [{
		                text: '保存',
		                handler: function() {
		                    if(!(userWinForm.form.isValid())) {
		                    	return false;
		                    } else {
		                    	if (isExist == true) {
				            		userWinForm.getForm().findField('username').markInvalid('该用户名已存在.');
				            		return false;
				            	}
		                    	userWinForm.getForm().submit({
									url: 'UserAction!userController.do',
									method: 'POST',
									submitEmptyText: false,
									params: {
										'user.cudType': cudType
									},
									success: function (result, request) {
										win.hide('userManager', function() {	// 淡入窗口
											refresh();	// 刷新
						                	win.close();						// 关闭
						                }, true);
									},
									failure: function (result, request) {
										Ext.MessageBox.alert('提示', '操作失败!');
						            }
								});
		                    }
		                }
		            },{
		                text: '取消',
		                handler: function() {
		                    win.hide('userManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
		                }
		            }],
					listeners: {
		        		beforerender: function(win) {//渲染前
	    					if(cudType == 'U') {//修改
				    			userWinForm.getForm().reset();
				       			userWinForm.getForm().setValues(Ext.getCmp('userForm').getForm().getValues());
				    		}
		        		}
		            }
		        });
		        win.show('userManager');// 淡出窗口
		        
	    	}
	    	
	    	function roleAuthorization(title, personId) {
				var recordsChecked = new Array();// 选中的Record列表 
	    		var store = new Ext.data.Store({//角色数据源
					proxy: new Ext.data.HttpProxy({
						url: 'UserAction!getSelectedRoleList.do'
					}),
					reader: new Ext.data.JsonReader({
						totalProperty: 'total',
						root: 'list'
					}, new Ext.data.Record.create([
						{name: 'id'},
			        	{name: 'roleName'},
					    {name: 'enableStatus'},
					    {name: 'checked'}
					])),
					remoteSort: false,//是否远程排序
					autoLoad: true,
					baseParams: {
						start: PAGING_START_INDEX,
						limit: 10,
						personId: personId
					},
					listeners : {
	                    load: function(store, records, options) {
	                        var arrays = new Array();
	                        store.each(function(record) {
	                            if (record.get('checked') == 'true') {
	                            	arrays.push(record);//将被选中的角色添加到集合
	                            }
	                        });
	                        selModel.selectRecords(arrays);//将集合内的进行选中
	                    }
					}
				});
				var RecordSet = Ext.data.Record.create([
					{name: 'personId'},
			    	{name: 'roleId'},
		    	   	{name: 'checked'}
			    ]);
				var selModel = new Ext.grid.CheckboxSelectionModel({
					listeners: {
						'rowselect': function(selModel, rowIndex, record) {//行选中
							var rs = new RecordSet({
				        		personId: personId,
				        		roleId: record.get('id'),
				        		checked: selModel.isSelected(rowIndex)
				        	});
				        	recordsChecked.push(rs);
						},
						'rowdeselect': function(selModel, rowIndex, record) {//取消选中
							var rs = new RecordSet({
				        		personId: personId,
				        		roleId: record.get('id'),
				        		checked: selModel.isSelected(rowIndex)
				        	});
				        	recordsChecked.push(rs);
						}
					}
				});
				var colModel = new Ext.grid.ColumnModel({
		    		defaults: {
			            sortable: true // 默认全部列可排序          
			        },
			        columns: [
			        	selModel,
			        	new Ext.grid.RowNumberer({
			        		id: 'rownum',
			        		header: '序号',
							width: 50,
							align: 'center'	
						}),{
			        		id: 'roleId',
							header: '主键ID',
							dataIndex: 'id',
							width: 25,
							align: 'center',
							hidden: true
						},{
			        		id: 'roleName',
				        	header: '角色名称',
				        	dataIndex: 'roleName',
				      		width: 100,
				           	align: 'center'
				        },{
				        	id: 'enableStatus',
				        	header: '状态',
				        	dataIndex: 'enableStatus',
				        	width: 50,
				        	align: 'center',
				        	renderer: function(value, cellmeta, record) {
				        		return cf_enableStatus(value);
				        	}
				        }
			        ]
			    });
		        var roleAuth = new Ext.grid.GridPanel({
		        	id: 'roleAuth',
			        autoScroll: true,
				    store: store,
				    cm: colModel,
				    sm: selModel,
				    frame: false,
				    trackMouseOver: true,//鼠标经过痕迹
				    loadMask: true,
		        	loadMask: {msg: 'loading...'},
				    tbar: ['->','角色名',
			        	new Ext.form.TwinTriggerField({
						    trigger1Class: 'x-form-clear-trigger',
						    trigger2Class: 'x-form-search-trigger',
						    hideTrigger1: true,
						    autoWidth: true,
						    listeners: {
						        'specialkey': function(f, e){
						        	if(e.getKey() == e.ENTER){
						            	this.onTrigger2Click();
						        	}
						    	}
						 	},
						 	onTrigger1Click:function(){
						    	this.setRawValue('');
						     	this.triggers[0].hide();
						    	return false;
						 	},
						 	onTrigger2Click:function(){
						    	var name = this.getRawValue().replace(/(^\s*)|(\s*$)/g, "");//去前后空格
					        	this.triggers[0].show();
						        store.reload({
						        	params: {
						        		start: PAGING_START_INDEX,
										limit: 10,
						        		roleName: name
						        	}
						    	});
							}
						})],
				    bbar: cf_getPagingToolbar(10, store),
				    viewConfig: {
		        		forceFit: true,//根据column进行百分比设置
		        		scrollOffset: 0//不加这个的话，会在grid的最右边有个空白，留作滚动条的位置。若不加默认为scrollOffset: 20
		        	}
		        });
	    		var win = new Ext.Window({
		            title: title,
		            layout: 'fit',
		            width: 320,
		            height: 360,
		            modal: true,
		            closeAction: 'close',
		            resizable: false,
		            items: roleAuth,
		            constrain: false,//禁止窗口移出浏览器
					constrainHeader: true,//禁止窗口移出浏览器
					buttonAlign: 'right',
					buttons: [{
						text: '确定',
						handler: function() {
							var records = filterDupFunctionRecord(recordsChecked);
            				if (recordsChecked.length < 1 || records.length < 1) {
					       		Ext.MessageBox.alert('提示', '数据没有任何改变!');
					       		return false;
					       	}
            				cf_ShowMessageBox('保存中..');
					       	var data = "[";
					       	for(var i = 0,len = records.length; i < len; i++) {
					       		data = data + "{personId:'" + records[i].get('personId') +
					       				"', roleId:'" + records[i].get('roleId') +
					       				"', checked:'" + records[i].get('checked') +
					            		"'}";
					            if (i < len - 1) {data = data + ",";}
					       	}
					       	data = data + "]";
					       	
					       	Ext.Ajax.request({
								url: 'UserAction!relationRoleController.do',
								method: 'POST',
								params: {jsonData: data},
								success: function (){
									Ext.MessageBox.alert('提示', '操作成功',
									function(btn) {
										win.hide('userManager', function(){
											refresh('center');
											win.close();
										} ,true);
									});
								},
								failure: function (){
									Ext.MessageBox.alert('提示', '操作失败');
					            }
							});	
            			}
					},{
						text: '取消',
						handler: function() {
							win.hide('userManager', function() {	// 淡入窗口
		                    	win.close();						// 关闭
		                    }, true);
						}
					}]
		        });
		        win.show('userManager');// 淡出窗口
	    	}
	    	
	    	function refresh() {
		    	personStore.modified = [];
	           	personStore.removeAll();
	  			personStore.reload();
		    }
	    	
	    	function getSelectPersonInfo() {
				return Ext.getCmp('personGrid').getSelectionModel().getSelected();
	    	}
	    	
	    	function filterDupFunctionRecord(receiveArray) {//过滤数组中的重复记录
			    var arrResult = new Array();//定义一个返回结果数组
			    for (var i = 0; i < receiveArray.length; i++) {
			        if (isDuplicateFunction(arrResult, receiveArray[i]) == -1) {//把不重复的记录放入新数组
			            arrResult.push(receiveArray[i]);
			        } else {//重复的记录取最后一个,因为要获得最后的选项
			        	arrResult.removeAt(isDuplicateFunction(arrResult, receiveArray[i]));
			        	arrResult.insert(i,receiveArray[i]);
			        }
			    }
			    return arrResult;
			}
	    	
	    	function isDuplicateFunction(receiveArray, checkItem) { //判断记录是否重复
			    var index = -1;  // 函数返回值用于布尔判断
			    for (var i = 0; i < receiveArray.length; i++) {
			        if (receiveArray[i].get('roleId') == checkItem.get('roleId')) {
			            index = i; //如果重复,返回当前index
			            break;
			        }
			    }
			    return index;
			}
	    	
	    });
    	
    </script>
  </head>
  
  <body>
    <div id="userManager"></div>
  </body>
</html>
